#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <cstdint>
#include "log.hpp"
using namespace std;

#define SIZE 1024

extern Log lg;
extern Translation_ T;

class Task
{
public:
    Task()
    {
    }

    Task(int sock, uint16_t port, string ip)
    : sock_(sock), port(port), ip(ip)
    {    
    }

    ~Task()
    {}
    
    void Run()
    {
        char buffer[SIZE];
        while (true)
        {
            int n = read(sock_, buffer, SIZE - 1);
            if (n > 0)
            {
                buffer[n] = 0; // 添加 '\0'
                string temp = buffer;
                cout << "TCP get a message:" << buffer << endl;
                string ret=T.Translate(temp);
                string info = "tcpserver echo#:" + ret;
                write(sock_, info.c_str(), info.size());
            }
            else if (n == 0)
            {
                lg("info", "%s:%d quit, server close sockfd: %d", ip.c_str(), port, sock_);
                break;
            }
            else
            {
                lg("Warning", "read error, sockfd: %d, client ip: %s, client port: %d", sock_, ip.c_str(), port);
                break;
            }
        }
    }

    void operator()()
    {
        Run();
    }

private:
    int sock_;
    uint16_t port;
    string ip;

    int result_;
    int exitcode_;
};